package com.idea.zd.sys.util.word;


import org.apache.commons.io.IOUtils;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlString;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;

import javax.xml.namespace.QName;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class XWPFRunHandler {

	/**
	 * 获取所有的文本内容
	 * @param run
	 * @return
	 */
	public static String getText(XWPFRun run) {
		CTR ctr = run.getCTR();
		int tArraySize = ctr.sizeOfTArray();
		if (tArraySize == 0) {
			return null;
		} else {
			StringBuffer text = new StringBuffer();
			for (int i = 0; i < tArraySize; i++) {
				text.append(ctr.getTArray(i).getStringValue());
			}
			return text.toString();
		}
	}

	/**
	 * 重新设置XWPFRun的文本内容
	 * @param run
	 * @param text
	 */
	public static void setText(XWPFRun run, String text){
		CTR ctr = run.getCTR();
		CTText textArray[] = getTextArray(ctr);
		if(textArray.length <= 0){
			setCTText(ctr.addNewT(),text);
		}else{
			int ta=0;
			if(text.indexOf("\r")>=0 || text.indexOf("\n")>=0){   //换行处理
				StringBuilder sb = new StringBuilder();
				for(int i=0, l=text.length(); i<l;  i++){
					char c = text.charAt(i);
					if(c=='\r'){
						if(sb.length()>0) {
							setCTText((ta++==0 ? textArray[0] : ctr.addNewT()), sb.toString());
							sb.setLength(0);
						}
						ctr.addNewBr();
					}else if(c=='\n'){
						if(sb.length()>0) {
							setCTText((ta++==0 ? textArray[0] : ctr.addNewT()), sb.toString());
							sb.setLength(0);
						}
						ctr.addNewCr();
					}else{
						sb.append(c);
					}
				}
				if(sb.length()>0) {
					setCTText((ta++==0 ? textArray[0] : ctr.addNewT()), sb.toString());
					sb.setLength(0);
				}
			}else{
				setCTText(textArray[0],text);
			}

			for (int i = 1; i < textArray.length; i++) {
				setCTText(textArray[i],"");
			}
		}
	}

	private static CTText[] getTextArray(CTR ctr) {
		int tArraySize = ctr.sizeOfTArray();
		CTText[] textArray = new CTText[tArraySize];
		for (int i = 0; i < tArraySize; i++) {
			textArray[i] = ctr.getTArray(i);
		}
		return textArray;
	}

	private static void setCTText(CTText cttext, String text){
		cttext.setStringValue(text);
		preserveSpaces(cttext);
	}

	private static void preserveSpaces(XmlString xs) {
        String text = xs.getStringValue();
        if (text != null && (text.startsWith(" ") || text.endsWith(" "))) {
            XmlCursor c = xs.newCursor();
            c.toNextToken();
            c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
            c.dispose();
        }
    }


    @SuppressWarnings("deprecation")
    public static void setPicture(XWPFRun run, DocPicture picInfo){
		try {
			setText(run, "");
			XWPFDocument document = run.getDocument();
			String bid = document.addPictureData(picInfo.getPicData(), picInfo.getPicType());
			((CustomXWPFDocument)document).createPicture(bid, document.getAllPictures().size() - 1, picInfo.getWidth(), picInfo.getHeight(), run.getParagraph());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    @SuppressWarnings("deprecation")
    public static void setPicture(XWPFRun run, String picInfo){
		String[] infos = picInfo.split(";");
		try {
			if(infos.length>0){
				File f = new File(infos[0]);
				if(!(f.exists() && f.isFile())){
					setText(run, picInfo);
					return;
				}
			}
			setText(run, "");
			if(infos.length>0) {
				String pic = infos[0];
//				String fileName = FilenameUtils.getName(pic);

				int picType = Document.PICTURE_TYPE_PNG;
				if(infos.length>1)
					picType = TypeCastUtils.convert2Integer(infos[1], Document.PICTURE_TYPE_PNG);
				int width = 200;
				if(infos.length>2)
					width = TypeCastUtils.convert2Integer(infos[2], 200);
				int height = 200;
				if(infos.length>3)
					height = TypeCastUtils.convert2Integer(infos[3], 200);
				XWPFDocument document = run.getDocument();
				FileInputStream in = new FileInputStream(pic);
				String oid =document.addPictureData(in, picType);
				((CustomXWPFDocument)document).createPicture(oid,document.getAllPictures().size() - 1, width, height, run.getParagraph());
				IOUtils.closeQuietly(in);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    @SuppressWarnings("deprecation")
    public static void setPicture(XWPFRun run, InputStream is, int picType, int width, int height){
		try {
			setText(run, "");
			XWPFDocument document = run.getDocument();
			String oid = document.addPictureData(is, picType);
			((CustomXWPFDocument)document).createPicture(oid,document.getAllPictures().size() - 1, width, height, run.getParagraph());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
